<template>
  <div v-loading="resultObj.loading">
    <el-card shadow="never">
      <div>
        <el-table :data="resultObj.distributionCannelData" border stripe style="width: 100%" class="j-table mt-0">
          <el-table-column prop="channel_value" label="渠道参数" />
          <el-table-column prop="type" label="渠道分类" />
          <el-table-column prop="user_count" label="用户数量" />
          <el-table-column prop="order_count" label="充值数量" />
          <el-table-column prop="order_amount" label="充值金额">
            <template #default="scope">
              <span>${{ scope.row.order_amount }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="j-pagination">
          <el-pagination
            background
            layout="prev, pager, next"
            :current-page="resultObj.distributionCannelPage"
            :pageSize="resultObj.distributionCannelLimit"
            :total="resultObj.distributionCannelTotal"
            @current-change="
              (val) => {
                onCurrentChange('distributionCannel', val);
              }
            "
          />
        </div>
      </div>
    </el-card>

    <!-- 编辑 -->
    <Edit ref="editRef" @confirm="onConfirm" />

    <!-- 结算 -->
    <Settlement ref="settlementRef" @confirm="onConfirm" />
  </div>
</template>

<script lang="ts" setup>
  import { computed, onMounted } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { setLang } from '@/i18n';
  import { useI18n } from 'vue-i18n';
  import { distributionInfoApi, distributionPayoffApi, distributionInviteApi, distributionUserApi, distributionStatusApi, distributionCannelApi } from '@/api/index';
  import type { FormInstance, FormRules } from 'element-plus';
  import dayjs from 'dayjs';
  import Edit from '../components/edit.vue';
  import Settlement from '../components/settlement.vue';

  const { locale } = useI18n();

  const route = useRoute();
  const router = useRouter();
  const userStore = useUserStore();

  const getUserInfo = computed(() => {
    let userInfo = userStore.getUserInfo || {};
    return userInfo;
  });

  const emits = defineEmits<{
    (event: 'confirm'): void;
  }>();

  const currentTab = ref('1');
  const currentSubTab = ref('1-1');

  const editRef = ref();
  const settlementRef = ref();

  const onTabChange = (val) => {
    if (val == '1') {
      onSubTabChange(currentSubTab.value);
    } else if (val == '2') {
      onCurrentChange('distributionUser', 1);
    } else if (val == '3') {
      onCurrentChange('distributionCannel', 1);
    }
  };

  const onSubTabChange = (val) => {
    if (val == '1-1') {
      onCurrentChange('distributionInvite', 1);
    } else if (val == '1-2') {
      onCurrentChange('distributionPayoff', 1);
    }
  };

  const resultObj = reactive({
    distributionInfo: {
      user_id: '',
      username: '',
      total_income: 0,
      income: 0,
      pay_income: 0,
      order_amount: 0,
      income_ratio: '',
    },
    distributionPayoffData: [],
    distributionInviteData: [],
    distributionUserData: [],
    distributionCannelData: [],
    distributionPayoffLimit: 20,
    distributionPayoffPage: 1,
    distributionPayoffTotal: 0,
    distributionInviteLimit: 20,
    distributionInvitePage: 1,
    distributionInviteTotal: 0,
    distributionUserLimit: 20,
    distributionUserPage: 1,
    distributionUserTotal: 0,
    distributionCannelLimit: 20,
    distributionCannelPage: 1,
    distributionCannelTotal: 0,
    loading: false,
    currentTab: '',
  });

  const getDistributionInfo = async () => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    resultObj.distributionInfo = {};
    distributionInfoApi({})
      .then((res) => {
        if (res.data) {
          resultObj.distributionInfo = res.data;
        }
        resultObj.loading = false;
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const getDistributionInvite = async () => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    resultObj.distributionInviteData = [];
    distributionInviteApi({
      limit: resultObj.distributionInviteLimit,
      page: resultObj.distributionInvitePage,
    })
      .then((res) => {
        if (res.data) {
          resultObj.distributionInviteData = res.data.list;
          resultObj.distributionInviteTotal = res.data.count;
        }
        resultObj.loading = false;
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const getDistributionPayoff = async () => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    resultObj.distributionPayoffData = [];
    distributionPayoffApi({
      limit: resultObj.distributionPayoffLimit,
      page: resultObj.distributionPayoffPage,
    })
      .then((res) => {
        if (res.data) {
          resultObj.distributionPayoffData = res.data.list;
          resultObj.distributionPayoffTotal = res.data.count;
        }
        resultObj.loading = false;
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const getDistributionUser = async () => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    resultObj.distributionUserData = [];
    distributionUserApi({
      limit: resultObj.distributionUserLimit,
      page: resultObj.distributionUserPage,
    })
      .then((res) => {
        if (res.data) {
          resultObj.distributionUserData = res.data.list;
          resultObj.distributionUserTotal = res.data.count;
        }
        resultObj.loading = false;
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const getDistributionCannel = async () => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    resultObj.distributionCannelData = [];
    distributionCannelApi({
      limit: resultObj.distributionCannelLimit,
      page: resultObj.distributionCannelPage,
    })
      .then((res) => {
        if (res.data) {
          resultObj.distributionCannelData = res.data.list;
          resultObj.distributionCannelTotal = res.data.count;
        }
        resultObj.loading = false;
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const onCurrentChange = (type, val) => {
    if (type == 'distributionInvite') {
      resultObj.distributionInvitePage = val;
      getDistributionInvite();
    } else if (type == 'distributionPayoff') {
      resultObj.distributionPayoffPage = val;
      getDistributionPayoff();
    } else if (type == 'distributionUser') {
      resultObj.distributionUserPage = val;
      getDistributionUser();
    } else if (type == 'distributionCannel') {
      resultObj.distributionCannelPage = val;
      getDistributionCannel();
    }
  };

  const onDisChange = (row) => {
    ElMessageBox.confirm('您确定改变该用户的分销功能状态吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        onDisChangeFn(row);
      })
      .catch(() => {});
  };

  const onDisChangeFn = async (row) => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    distributionStatusApi({ user_id: row.user_id })
      .then((res) => {
        resultObj.loading = false;
        if (res.errcode == 0) {
          ElMessage.success(res.message || res.errmsg);
          getDistributionUser();
        } else {
          ElMessage.error(res.message || res.errmsg);
        }
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const parseTime = (val: string) => {
    return val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '';
  };

  const onAdd = async (row) => {
    editRef.value.onOpen(row, 'add');
  };

  const onEdit = async (row) => {
    editRef.value.onOpen(row, 'edit');
  };

  const onSettlement = async (row) => {
    settlementRef.value.onOpen(row);
  };

  const onConfirm = () => {
    getDistributionUser();
  };

  onMounted(() => {
    resultObj.distributionCannelPage = 1;
    getDistributionCannel();
  });
</script>

<style scoped lang="scss"></style>
